package app.controller.wechat.scanlogin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


public class ScanStore {
	private static Map<String, Machine> KV=new ConcurrentHashMap<>();
	public static Map<String, Object> s=new ConcurrentHashMap<>();
	public static class Machine{
		private String machineKey;
		private boolean isCorrect=false;
		private long createTime=System.currentTimeMillis();
		
		public Machine(String machineKey){
			this.machineKey=machineKey;
		}
		
		public Machine(String machineKey, boolean isCorrect, long createTime) {
			this.machineKey = machineKey;
			this.isCorrect = isCorrect;
			this.createTime = createTime;
		}
		public String getMachineKey() {
			return machineKey;
		}
		public void setMachineKey(String machineKey) {
			this.machineKey = machineKey;
		}
		public boolean isCorrect() {
			return isCorrect;
		}
		public void setCorrect(boolean isCorrect) {
			this.isCorrect = isCorrect;
		}
		public long getCreateTime() {
			return createTime;
		}
		public void setCreateTime(long createTime) {
			this.createTime = createTime;
		}
		public boolean isUpto(){
			return createTime+1*60*1000L>=System.currentTimeMillis();
		}
	}
	public static boolean isUpto(String machineKey){
		if (machineKey==null||"".equals(machineKey)) {
			return false;
		}
		Machine machine = KV.get(machineKey);
		if (machine==null) {
			return true;
		}
		
		return !machine.isUpto();
	}
	
	public static boolean isCorrect(String machineKey){
		Machine machine = KV.get(machineKey);
		if (machine != null) {
			if (machine.isUpto()) {
				if (machine.isCorrect()) {
					KV.remove(machineKey);
					return true;
				}
			}
		}
		return false;
	}
	
	public static void changeMachine(String machineKey){
		Machine machine = KV.get(machineKey);
		if (machine!=null) {
			machine.setCorrect(true);
			KV.put(machineKey, machine);
		}
	}
	
	public static void Machine(String machineKey){
		int del = del(KV);
		System.out.println("机器有："+del+"台，因时间过期删除");
		KV.put(machineKey, new Machine(machineKey));
	}
	
	private static int del(Map<String, Machine> KVT){
		int count=0;
		Set<String> MachineSet = KVT.keySet();
		List<String> machines=new ArrayList<>(MachineSet);
		for(String machineKey:machines){
			if (!KVT.get(machineKey).isUpto()) {
				KVT.remove(machineKey);
				count+=1;
			}
		}
		return count;
	}
}
